#!/usr/bin/env python
# -*- coding:utf8 -*-
import sys
import requests
import re
import datetime

from harborclient import HarborClient
from harborclient import logging
host = "192.168.10.96:8080"
user = "admin"
passwd = "Harbor12345"
#token = "11MIzzoCqt3KNhyXzfam3b1+aTP+RCEf1AclB1zrvDZQM08HOausHhCJzUzxFs+O3Vc7PBnEbm4iMvxoxlLBnw=="
#sid = "1214108e0e162df2b6155bb0e0096b47"
sid = "5726d7b95bbc33998fec144090df9785"
del_image = []
retain_image = []


class harborlog(HarborClient):

    def get_retentions_executions(self, id):
        result = False
        path = '{}://{}/api/v2.0/retentions/{}/executions'.format(
            self.protocol, self.host, id)
        response = requests.get(
            path, cookies={'sid': self.session_id})

        if response.status_code == 200:
            result = response.json()
            logging.debug(
                'Successfully to get retentions executions {} '.format(path))
        else:
            logging.error(
                'Failed to get retentions executions {}'.format(path))
        return result

    def get_retentions_executions_task(self, id, eid):
        result = False
        path = '{}://{}/api/v2.0/retentions/{}/executions/{}/tasks'.format(
            self.protocol, self.host, id, eid)
        response = requests.get(
            path, cookies={'sid': self.session_id})

        if response.status_code == 200:
            result = response.json()
            logging.debug(
                'Successfully to get retentions executions {} '.format(path))
        else:
            logging.error(
                'Failed to get retentions executions {}'.format(path))
        return result

    def get_retentions_executions_log(self, id, eid, tid):
        result = False
        path = '{}://{}/api/v2.0/retentions/{}/executions/{}/tasks/{}'.format(
            self.protocol, self.host, id, eid, tid)
        response = requests.get(
            path, cookies={'sid': self.session_id})

        if response.status_code == 200:
            result = response.iter_lines()
            logging.debug(
                'Successfully to get_retentions_executions_log {} '.format(path))
        else:
            logging.error(
                'Failed to get_retentions_executions_log {}'.format(path))
        return result


def get_cleanup_image(log):
    other = []
    for line in log:
        print line
        # info = re.findall(r"DEl", line)
        if re.findall(r"DEl", line):
            del_image.append(line)
        elif re.findall(r"RETAIN", line):
            retain_image.append(line)
        else:
            other.append(line)
    if len(other) == 8:
        return True
    else:
        print other


def print_list(list):
    for info in list:
        print info


def main():
    if len(sys.argv) >1:
        session = sys.argv[1]
    else:
        session = sid
    today = datetime.datetime.today().strftime("%Y-%m-%d")
    c = harborlog(host=host, user=user, password=passwd,
                  protocol="http", verify_ssl_cert=False,  sessions=session)
    if not c:
        return ""
    projects = c.get_projects()
    print projects
    for each_project in projects:
        pid = each_project.get("project_id")
        detail_info = c.get_project_detailed_info(pid)
        rid = detail_info.get("metadata", {}).get("retention_id")
        if not rid:
            # 如果没有获取到id，则直接跳过
            print "not get rid, continue project:%s" % (
                detail_info.get("name"))
            continue
        detail_info = c.get_retentions_executions(rid)
        if not detail_info:
            continue
        executions = sorted(detail_info, key=lambda item: int(
            item["id"]), reverse=True)
        for each_executions in executions:

        #    if each_executions.get("start_time")[:10] != today:
        #        break
            eid = each_executions["id"]
            tasks = c.get_retentions_executions_task(rid, eid)
            for each_tasks in tasks:
                tid = each_tasks["id"]
                log = c.get_retentions_executions_log(rid, eid, tid)
                if not log:
                    continue
                get_cleanup_image(log)
    print "*************************************DEL IMAGE*************************************************************"
    print print_list(del_image)
    print ""
    print ""
    print ""
    print ""
    print ""
    print ""
    print "*************************************RETAIN IMAGE*************************************************************"
    print print_list(retain_image)
    if len(del_image) != 0:
        exit(-1)


if __name__ == "__main__":
    main()
    print 1111111111111
